package util;

import com.fasterxml.jackson.databind.ObjectMapper;
import domain.Book;
import domain.User;
import service.BookService;
import service.UserService;
import service.impl.BookServiceImpl;
import service.impl.UserServiceImpl;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ServletUtil {
    public  static User checkLogin(HttpServletRequest request){
        Map<String,String> loginCookies = new HashMap<>(8);
        UserService us = new UserServiceImpl();
        Boolean isLogin;
        Cookie[] cookies = request.getCookies();
        for(Cookie cookie:cookies){
            String name = cookie.getName();
            if("PWM".equals(name) || "UNM".equals(name) ||"uid".equals(name)){
                loginCookies.put(name,cookie.getValue());
            }
        }
        if(loginCookies.size()<3){
            //登录所需cookies缺少
            isLogin =false;
        }else {
            //验证cookies信息是否正确
            isLogin = us.checkUserloginCookies(loginCookies.get("PWM"), loginCookies.get("UNM"), Integer.parseInt(loginCookies.get("uid")));
        }
        if(isLogin){
            return us.getUserInfo(Integer.parseInt(loginCookies.get("uid")));
        }
        return null;
    }
    public static Book checkBook(User user,int bid){
        UserService us = new UserServiceImpl();
        BookService bs = new BookServiceImpl();
        List<Book> userbook = us.getUserbook(user);
        Book book = bs.getBookbybid(bid);
        if(book==null){
            return null;
        }
        int bookUid = book.getUid();
        if(bookUid==user.getUid() || bookUid==0){
            //用户与书籍相匹配或为0号管理员上传的书籍
            return book;
        }
        return null;
    }
}
